<?php
/**
 * tpAdmin [a web admin based ThinkPHP5]
 *
 * @author yuan1994 <tianpian0805@gmail.com>
 * @link http://tpadmin.yuan1994.com/
 * @copyright 2016 yuan1994 all rights reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */

//------------------------
// 新闻列表
//-------------------------

namespace app\admin\controller;
\think\Loader::import('controller/Jump', TRAIT_PATH, EXT);
use app\admin\Controller;
use think\Db;
use think\Lang;
use think\Loader;
use think\Exception;

class News extends Controller
{
	use \traits\controller\Jump;
    use \app\admin\traits\controller\Controller;
	
    public function __construct(){
        parent::__construct();
        $newsType = Db::table("tp_news_type")->select();
        $this->view->assign("newsType", $newsType);
    }
    /**
     * 列表
     */
    public function index()
    {
        $model = $this->getModel('news');
        $map = array();
        // id
        if ($this->request->param('id'))   $map['id'] = ['eq',   $this->request->param('id')  ];
        // 标题
        if ($this->request->param('title'))  $map['title'] = ['eq',   $this->request->param('title') ];
        // 查询字段
       // $field = 'n.id,n.typeid,n.title,n.content,n.pic,n.addtime,t.title as typetitle';
        $listRows = 20;
        $map['isdelete'] = 0;					
        // 分页查询       
        $list = $model->where($map)->field('*')->order('id desc')->paginate($listRows,false,['query'=>$this->request->get()]);
	  
//      $list = $model->alias('n')->field($field)		
//          ->join([
//              ['tp_news_type t', 'n.typeid=t.id', 'LEFT']
//          ])
//          ->where($map)->order('id desc')->paginate($listRows, false, ['query' => $this->request->get()]);

        // 模板赋值显示
//    	if($list){     		
//    		foreach($list as $k => $v){				
//    			$list[$k]['pic'] =  str_replace("\\", '/', $list[$k]['pic']);
//				var_dump($list[$k]['pic']);
//				echo '<br>';				
//    		}      		
//    	}
		
		//dump($list);exit;
        $this->view->assign('list', $list);
        $this->view->assign("page", $list->render());
        $this->view->assign("count", $list->total());
        $this->view->assign('numPerPage', $listRows);

        return $this->view->fetch();
    }

	public function add(){
		if(request()->isPost()){
			$data = input('post.');
			$data['addtime'] = time();
			//dump($data['addtime']);
			//exit;
			$res = Db::table('tp_news')->insert($data);
			if($res){
				return ajax_return_adv('添加成功');
			}else{
				return ajax_return_adv_error('添加失败');
			}
		}		
		return view();
	}

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $controller = $this->request->controller();
        $module = $this->request->module();

        if ($this->request->isAjax()) {
            // 更新
            $data = $this->request->post();
            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            }
     
            // 验证
            if (class_exists(Loader::parseClass($module, 'validate', $controller))) {
                $validate = Loader::validate($controller);
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }
            // 更新数据
            Db::startTrans();
            try {
                $data['addtime'] = time();
                Db::table("tp_news")->where(" id = ".$data['id'])->update($data);
                // 提交事务
                Db::commit();

                return ajax_return_adv("编辑成功");
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return ajax_return_adv_error($e->getMessage());
            }
        } else {
            // 编辑
            $id = $rId = $this->request->param('id');
            if (!$id) {
                throw new Exception("缺少参数ID");
            }
            $vo = $this->getModel($controller)->find($rId);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }
            $this->view->assign("vo", $vo);

            return $this->view->fetch();
        }
    }


	public function thumb(){	
		$id = request()->param('id');
  		//dump($id);
		$res = db('news')->where('id',$id)->find();
		$this->view->assign('data',$res);		
		return view();
	}

	/*
	 * 裁剪单个图片
	 */
	public function updatethumb(){
		if(request()->isPost()){
			$data = input('post.');
			$result = db('news')->where('id',$data['id'])->find();
			//如果裁剪过  再次裁剪则先删除以前裁剪好的图片
			//dump($result);
			if(file_exists(ROOT_PATH.'public/'.$result['phone'])){
				$res = @unlink(ROOT_PATH.'public/'.$result['phone']); //返回bool型
				//dump($res);exit;
			}
							
			$base64 = $data['phone'];
			//var_dump($base64);die;					
			$base64_body = substr(strstr($base64,','),1);
			$img = base64_decode($base64_body);	
			$path ='./tmp/uploads/news/';
			if(!file_exists($path)){
				mkdir($path,0777,true);
			}
			$aa = substr(md5($path.time()), 8, 16) .".png";	
			//dump($path);		
			$path = './tmp/uploads/news/'.$aa;			
			//dump($path);exit;
			$path = str_replace("\\","/",$path);
			file_put_contents($path, $img);
			$path = '/tmp/uploads/news/'.$aa;	
		 	$data['phone'] = $path;
			$data['clip'] = 1; 									
				
			$res = Db::table('tp_news')->where('id',$data['id'])->update($data);											
			if($res)  $this->success('裁剪成功','news/index');				    				
			else   $this->error('裁剪失败，请重新裁剪');						
					
		}	
		return $this->view0>fetch('index');
	}


	function del(){
		$model = $this->getModel('news');
		$id = request()->param('id');		
		$res = $model->where('id',$id)->find();
		$path1 = $res['pic'];
		$path2 = $res['phone'];
			
		$result = $model->where('id',$id)->delete();
		if($result){
			static $a = 1;
			if(file_exists(ROOT_PATH."public/".$path1)){
				@unlink(ROOT_PATH."public/".$path1);	
				$a = 2;		
			}
			if(file_exists(ROOT_PATH.'public/'.$path2)){
				@unlink(ROOT_PATH.'public/'.$path2);
				$b = 2;
			}				
			if($a){
				return ajax_return_adv('删除成功');
			}											
		}else{
			return ajax_return_adv_error("删除失败");
		}			
		return view();
	}












}